package com.example.mvc_test.initialzer;

import com.example.mvc_test.config.MyConfig;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;

/**
 * @description 替代web.xml
 * @author ljw
 * @date 2021/9/15 7:55
 */
public class WebInitialzer implements WebApplicationInitializer {

    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        //创建注解配置应用上下文
        AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
        //注册配置类
        context.register(MyConfig.class);
        //设置上下文
        context.setServletContext(servletContext);
        //设置核心处理器dispatcher
        ServletRegistration.Dynamic dispatcher = servletContext.addServlet("dispatcher", new DispatcherServlet(context));
        //设置映射路径
        dispatcher.addMapping("/");
        //设置加载顺序
        dispatcher.setLoadOnStartup(1);
    }
}
